package com.wing.qualityTesting.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wing.common.enums.MaintenanceEnum;
import com.wing.common.enums.ProductEnum;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.CodeUtil;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.enterprise.feign.EnterpriseClient;
import com.wing.productionPlan.dao.DynamicDao;
import com.wing.productionPlan.dao.QualityTestingRecordDetailDao;
import com.wing.productionPlan.model.entity.ProAbnormalCause;
import com.wing.productionPlan.model.entity.ProductionTheWorkOrder;
import com.wing.productionPlan.model.entity.ProductionWorkOrder;
import com.wing.productionPlan.model.entity.QualityTestingRecordDetail;
import com.wing.productionPlan.model.request.QualityTestingRecordDetailForm;
import com.wing.productionPlan.model.response.ProductionWorkOrderVO;
import com.wing.productionPlan.model.response.QualityTestingRecordDetailVO;
import com.wing.productionPlan.service.ProductionTheWorkOrderService;
import com.wing.productionPlan.service.ProductionWorkOrderService;
import com.wing.productionPlan.service.QualityTestingRecordDetailService;
import com.wing.qualityTesting.dao.QualityTestingRecordDao;
import com.wing.qualityTesting.model.entity.QualityTestingRecord;
import com.wing.qualityTesting.model.entity.QualityTestingRecordValue;
import com.wing.qualityTesting.model.entity.QualityTestingTaskError;
import com.wing.qualityTesting.model.entity.WorkOrderQualityTestingTask;
import com.wing.qualityTesting.model.request.*;
import com.wing.qualityTesting.model.response.*;
import com.wing.user.feign.UserClient;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;


/**
 * 质检记录表-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class QualityTestingRecordServiceImpl extends ServiceImpl<QualityTestingRecordDao, QualityTestingRecord> implements QualityTestingRecordService {

    @Autowired
    private WorkOrderQualityTestingTaskService workOrderQualityTestingTaskService;
    @Autowired
    private ProductionWorkOrderService productionWorkOrderService;
    @Autowired
    private QualityTestingTaskErrorService qualityTestingTaskErrorService;
    @Autowired
    private ProductionTheWorkOrderService productionTheWorkOrderService;
    @Autowired
    private ProcessQualityService processQualityService;
    @Autowired
    private ProcessQualityValueService processQualityValueService;
    @Autowired
    private DynamicDao dynamicDao;
    @Autowired
    private QualityTestingRecordDetailService qualityTestingRecordDetailService;
    @Autowired
    private QualityTestingRecordValueService qualityTestingRecordValueService;

    @Autowired
    private EnterpriseClient enterpriseClient;

    @Autowired
    private UserClient userClient;

    @Autowired
    private QualityTestingRecordDetailDao qualityTestingRecordDetailDao;

    @Override
    public int add(QualityTestingRecordForm qualityTestingRecordForm) {

        //校验

        QualityTestingRecord qualityTestingRecord = new QualityTestingRecord();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(QualityTestingRecord.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(qualityTestingRecordForm, qualityTestingRecord, copyOptions);

        return baseMapper.insert(qualityTestingRecord);
    }

    @Override
    public List<QualityTestingRecordVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<QualityTestingRecordVO> pageList4app(Page page, Map<String, Object> params) {
        List<QualityTestingRecordVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public QualityTestingRecordVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    public WorkOrderQualityTestingTaskVO getTestingTaskByTaskId(Long taskId) {
        return baseMapper.getTestingTaskByTaskId(taskId);
    }

    @Override
    public List<ProcessQualityVO> getInspectionResultsData(Long taskId) {
        WorkOrderQualityTestingTaskVO qualityTestingTaskVO = workOrderQualityTestingTaskService.get4appById(taskId);
        ProductionWorkOrderVO workOrderVO = productionWorkOrderService.get4appById(qualityTestingTaskVO.getWorkOrderId(), null);
        //查询质检名
        Map paramMap = new HashMap();
        paramMap.put("productTypeId", workOrderVO.getProductTypeId());
        paramMap.put("processId", workOrderVO.getProcessId());
        paramMap.put("categoryId", qualityTestingTaskVO.getTestingCategoryName());
        paramMap.put("deleted", 1);
        List<ProcessQualityVO> processQualityList = processQualityService.list4app(paramMap);
        //查询质检参数
        for (ProcessQualityVO item : processQualityList) {
            List<ProcessQualityValueVO> qualityValueList = processQualityValueService.getQualityValueList(item.getId());
            if (CollectionUtils.isNotEmpty(qualityValueList)) {
                item.setQualityValueVOList(qualityValueList);
            }
        }

        return processQualityList;
    }

    @Transactional
    @Override
    public void submitTestingRecord(QualityTestingRecordForm qualityTestingRecordForm) {
        WorkOrderQualityTestingTask testingTask = workOrderQualityTestingTaskService.getById(qualityTestingRecordForm.getQualityTestingTaskId());
        if (testingTask == null) {
            throw new BusinessException("质检任务不存在");
        }
        ProductionWorkOrderVO workOrderVO = productionWorkOrderService.get4appById(testingTask.getWorkOrderId(), null);
        QualityTestingRecord qualityTestingRecord = new QualityTestingRecord();
        //添加质检记录
        String today = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
        Integer maxNo = dynamicDao.getDayMaxNo("ord_quality_testing_record");
        String code = CodeUtil.getCode(maxNo);
        qualityTestingRecord.setCode("ZJ" + workOrderVO.getCode() + code);
        qualityTestingRecord.setNo(Integer.valueOf(code));
        qualityTestingRecord.setDay(Integer.valueOf(today));
        qualityTestingRecord.setQualityTestingTaskId(testingTask.getId());
        qualityTestingRecord.setEnterpriseCode(JwtUtils.getEnterpriseCode());
        qualityTestingRecord.setWorkOrderId(testingTask.getWorkOrderId());
        qualityTestingRecord.setRemark(qualityTestingRecordForm.getRemark());
        qualityTestingRecord.setCreatorName(JwtUtils.getLoginUsername());
        baseMapper.insert(qualityTestingRecord);
        //质检记录详情
        if (CollectionUtils.isEmpty(qualityTestingRecordForm.getTestingRecordDetail())) {
            throw new BusinessException("质检参数结果异常");
        }
        for (QualityTestingRecordDetailForm item : qualityTestingRecordForm.getTestingRecordDetail()) {
            QualityTestingRecordDetail qualityTestingRecordDetail = new QualityTestingRecordDetail();
            CopyOptions copyOptions = CopyOptions.create()
                    .setEditable(QualityTestingRecordDetail.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(item, qualityTestingRecordDetail, copyOptions);
            qualityTestingRecordDetail.setQualityTestingRecordId(qualityTestingRecord.getId())
                    .setQualityTestingTaskId(testingTask.getId())
                    .setCreatorName(JwtUtils.getLoginUsername())
                    .setProcessId(workOrderVO.getProcessId());
            qualityTestingRecordDetailService.save(qualityTestingRecordDetail);

            for (QualityTestingRecordValueForm valueItem : item.getQualityValueList()) {
                QualityTestingRecordValue recordValue = new QualityTestingRecordValue();
                recordValue.setProcessQualityId(valueItem.getProcessQualityId());
                recordValue.setProcessQualityValueId(valueItem.getProcessQualityValueId());
                recordValue.setProcessQualityName(valueItem.getProcessQualityName());
                recordValue.setProcessQualityValueName(valueItem.getProcessQualityValueName());
                recordValue.setTestingRecordDetailId(qualityTestingRecordDetail.getId());
                qualityTestingRecordValueService.save(recordValue);
            }
            //修改质检任务状态
            testingTask.setStatus(WorkOrderQualityTestingTask.Status.finish);
            workOrderQualityTestingTaskService.updateById(testingTask);
        }
    }

    /**
     * 添加质检记录
     *
     * @param form
     * @return
     */
    @Override
    @Transactional
    public int addQualityDetail(QualityRecordAddOrUpdateForm form) {
        //查询质检信息
        Long qualityTestingTaskId = form.getQualityTestingTaskId();
        WorkOrderQualityTestingTaskNeedVo byId = this.workOrderQualityTestingTaskService.getNeedInfoBy(qualityTestingTaskId);
        //1.先加入记录
        QualityTestingRecord record = new QualityTestingRecord();
        Integer maxNo = dynamicDao.getDayMaxNo("ord_quality_testing_record");
        String code = CodeUtil.getCode(maxNo);
        record.setCode(UniqueIdGeneratorUtil.generateUniqueId("ZJ", "yyyyMMdd", 1000, 9999));
        record.setNo(Integer.valueOf(code));
        String today = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
        record.setDay(Integer.valueOf(today));
        record.setQualityTestingTaskId(form.getQualityTestingTaskId());
        record.setRemark(form.getRemark());
        record.setCreatorName(JwtUtils.getLoginUsername());
        record.setCreator(JwtUtils.getLoginUserId());
        record.setInspectDeviceCode(form.getInspectDeviceCode());
        record.setCreateTime(LocalDateTime.now());
        record.setEnterpriseCode(JwtUtils.getEnterpriseCode());
        record.setWorkOrderId(form.getWorkOrderId());
        boolean save = save(record);
        if (save) {
            List<QualityRecordDetailInfoForm> detailList = form.getDetailList();
            List<QualityTestingRecordDetail> list = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(detailList)) {
                detailList.forEach(info -> {
                    QualityTestingRecordDetail detail = new QualityTestingRecordDetail();
                    Integer maxNoDt = dynamicDao.getDayMaxNo("ord_quality_testing_record_detail");
                    String codeDt = CodeUtil.getCode(maxNoDt);
                    detail.setCode(UniqueIdGeneratorUtil.generateUniqueId("ZJD", "yyyyMMdd", 100, 999));
                    detail.setNo(Integer.valueOf(codeDt));
                    String todayDt = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
                    detail.setDay(Integer.valueOf(todayDt));
                    detail.setCreatorName(JwtUtils.getLoginUsername());
                    detail.setCreator(JwtUtils.getLoginUserId());
                    detail.setCreateTime(LocalDateTime.now());
                    detail.setInspectDeviceCode(form.getInspectDeviceCode());
                    detail.setSampleCode(info.getSampleCode());
                    detail.setQualityTestingRecordId(record.getId());
                    detail.setQualityTestingTaskId(form.getQualityTestingTaskId());
                    detail.setInspectDeviceCode(info.getInspectDeviceCode());
                    detail.setProcessId(form.getProcessId());
                    detail.setRemark(info.getRemark());
                    detail.setProcessName(form.getProcessName());
                    detail.setStatus("1");
                    list.add(detail);
                });

                List<Map<String, Object>> mapList = new ArrayList<>();
                JsonResult proQualityProjectBy = enterpriseClient.getProQualityProjectBy(form.getBookId());
                if (proQualityProjectBy.getCode() == 200) {
                    ObjectMapper objectMapper = new ObjectMapper();
                    Object data = proQualityProjectBy.getData();
                    mapList = objectMapper.convertValue(data, new TypeReference<List<Map<String, Object>>>() {
                    });
                }
                //批量添加任务样品信息
                if (CollectionUtils.isNotEmpty(list)) {
                    boolean b = this.qualityTestingRecordDetailService.saveBatch(list);
                    if (b) {
                        if (ProductEnum.qualityNatureEmum.CPZJ.getCode().equals(byId.getQualityTestingNatureId())) {
                            int count = 0;
                            for (QualityTestingRecordDetail detail : list) {
                                //拿到skuCode  查询 质检项目
                                List<QualityTestingRecordValue> infoVos = new ArrayList();
                                for (Map<String, Object> stringObjectMap : mapList) {
                                    QualityTestingRecordValue infoVo = new QualityTestingRecordValue();
                                    infoVo.setCreatorName(JwtUtils.getLoginUsername());
                                    infoVo.setCreator(JwtUtils.getLoginUserId());
                                    infoVo.setCreateTime(LocalDateTime.now());
                                    infoVo.setProcessQualityId(Long.valueOf((String) stringObjectMap.get("id")));
                                    infoVo.setProcessQualityName((String) stringObjectMap.get("name"));
                                    infoVo.setTestingRecordDetailId(detail.getId());
                                    infoVo.setProcessQualityValueName("");
                                    infoVo.setRemark("");
                                    infoVo.setFileUrl("");
                                    infoVo.setFileName("");
                                    Integer maxNoValue = dynamicDao.getDayMaxNo("ord_quality_testing_record_value");
                                    String todayValue = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
                                    infoVo.setDay(Integer.valueOf(todayValue));
                                    infoVos.add(infoVo);
                                }
                                boolean saveBatch = qualityTestingRecordValueService.saveBatch(infoVos);
                                if (saveBatch) {
                                    count += 1;
                                }
                            }
                            if (count == list.size()) {
                                return 1;
                            }
                        }
                    }
                }
            }
        }
        return 0;
    }


    /**
     * 查询 - 任务记录下的样品配置
     *
     * @param
     * @return
     */
    @Override
    public List<QualityRecordDetailInfoVo> getRecordResultsData(Long recordId, Long processId) {
        QueryWrapper<QualityTestingRecordDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("quality_testing_record_id", recordId);
        if (null != processId) {
            queryWrapper.eq("process_id", processId);
        }
        List<QualityRecordDetailInfoVo> vos = new ArrayList<>();
        List<QualityTestingRecordDetail> list = qualityTestingRecordDetailService.list(queryWrapper);
        list.forEach(info -> {
            QualityRecordDetailInfoVo vo = new QualityRecordDetailInfoVo();
            BeanUtil.copyProperties(info, vo);
            if (info.getQualityTestingResult() != null) {
                if ("qualified".equals(info.getQualityTestingResult().name())) {
                    vo.setQualityTestingResultName("合格");
                } else if ("unqualified".equals(info.getQualityTestingResult().name())) {
                    vo.setQualityTestingResultName("不合格");
                } else {
                    vo.setQualityTestingResultName("其他");
                }
            }
            vos.add(vo);
        });
        return vos;
    }

    /**
     * 修改样品配置信息
     *
     * @param qualityTestingRecordForm
     * @return
     */
    @Override
    @Transactional
    public int updateQualityDetail(QualityRecordAddOrUpdateForm qualityTestingRecordForm) {
        QualityTestingRecord byId = this.getById(qualityTestingRecordForm.getId());
        byId.setUpdateTime(LocalDateTime.now());
        byId.setModifier(JwtUtils.getLoginUserId());
        byId.setModifierName(JwtUtils.getLoginUsername());
        boolean b = updateById(byId);
        QueryWrapper<QualityTestingRecordDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("process_id", qualityTestingRecordForm.getProcessId());
        queryWrapper.eq("quality_testing_record_id", qualityTestingRecordForm.getId());
        List<QualityTestingRecordDetail> list = qualityTestingRecordDetailService.list(queryWrapper);
        if (b) {
            List<QualityRecordDetailInfoForm> detailList = qualityTestingRecordForm.getDetailList();
            if (CollectionUtils.isNotEmpty(detailList)) {
                for (QualityRecordDetailInfoForm form : detailList) {
                    for (QualityTestingRecordDetail detail : list) {
                        if (detail.getId().equals(form.getId())) {
                            detail.setSampleCode(form.getSampleCode());
                            detail.setInspectDeviceCode(form.getInspectDeviceCode());
                            detail.setRemark(form.getRemark());
                        }
                    }
                }
            }

        }
        boolean b1 = this.qualityTestingRecordDetailService.updateBatchById(list);
        if (b1) {
            return 1;
        }
        return 0;
    }

    /**
     * 根据质检任务查询 质检信息
     *
     * @param taskId
     * @param recordDetailId
     * @return
     */
    @Override
    public QualityDetailRecordInfoVo getDetailRecordValue(Long taskId, Long recordDetailId, Long bookId) {
        //查询任务记录信息
        QualityDetailRecordInfoVo recordInfoVo = this.qualityTestingRecordDetailService.getDetailRecordValue(taskId, recordDetailId);
        if (ObjectUtil.isNotEmpty(recordInfoVo)) {
            recordInfoVo.setStatusDesc(ProductEnum.qualityStatusEmum.getNameByCode(recordInfoVo.getJCStatus()));
            // 先用详情和基准书 查询数据是否已经质检过  质检过的直接带出来
            //否则用工序名称 和 基准书查询
            List<QualityDetailValueInfoVo> processCheckValueList = qualityTestingRecordDetailDao.getProcessCheckValueList(recordDetailId);
            if (CollectionUtils.isNotEmpty(processCheckValueList)) {
                recordInfoVo.setDetailValueInfoVos(processCheckValueList);
            } else {
                Long processId = this.productionWorkOrderService.getProcessIdForWork(recordInfoVo.getWorkId());
                List<QualityDetailValueInfoVo> lists = qualityTestingRecordDetailDao.getProcessCheckProject(recordInfoVo.getBookId(), processId);
                recordInfoVo.setDetailValueInfoVos(lists);
            }
            //查询取值记录信息
         /*   List<QualityDetailValueInfoVo> infoVos = this.qualityTestingRecordValueService.listRecordValues(recordDetailId);
            if (CollectionUtils.isEmpty(infoVos)) {
                if (ObjectUtil.isNotEmpty(bookId)){
                    //如果为空 并且性质为成品质检
                    if (ProductEnum.qualityNatureEmum.CPZJ.getName().equals(recordInfoVo.getQualityTestingNatureName())
                            || ProductEnum.qualityNatureEmum.GXCP.getName().equals(recordInfoVo.getQualityTestingNatureName())) {


                        //拿到skuCode  查询 质检项目
                        JsonResult proQualityProjectBy = enterpriseClient.getProQualityProjectBy(bookId);
                        if (proQualityProjectBy.getCode() == 200) {


                            ObjectMapper objectMapper = new ObjectMapper();
                            Object data = proQualityProjectBy.getData();
                            List<Map<String, Object>> mapList = objectMapper.convertValue(data, new TypeReference<List<Map<String, Object>>>() {
                            });
                            for (Map<String, Object> stringObjectMap : mapList) {
                                QualityDetailValueInfoVo infoVo = new QualityDetailValueInfoVo();
                                infoVo.setFileName("");
                                infoVo.setFileUrl("");
                                infoVo.setWay((String) stringObjectMap.get("way"));
                                infoVo.setUtensil((String) stringObjectMap.get("utensil"));
                                infoVo.setStandard((String) stringObjectMap.get("standard"));
                                infoVo.setProcessQualityId(Long.valueOf((String) stringObjectMap.get("id")));
                                infoVo.setProcessQualityName((String) stringObjectMap.get("name"));
                                infoVo.setTestingRecordDetailId(recordDetailId);
                                infoVo.setProcessQualityValueName("");
                                infoVo.setRemark("");
                                infoVos.add(infoVo);
                            }
                            recordInfoVo.setDetailValueInfoVos(infoVos);



                        }
                    }
                }
            }
            //如果不为空直接取值
            else {
                recordInfoVo.setDetailValueInfoVos(infoVos);
            }*/
        }
        return recordInfoVo;
    }

    /**
     * 提交质检结果信息
     *
     * @param simpleVo
     * @return
     */
    @Override
    @Transactional
    public int submitResultValue(QualityDetailRecordSimpleVo simpleVo) {
        //查询补全原来的记录信息
        QualityTestingRecordDetail detailServiceById = qualityTestingRecordDetailService.getById(simpleVo.getRecordId());
        detailServiceById.setUpdateTime(LocalDateTime.now());
        detailServiceById.setModifier(JwtUtils.getLoginUserId());
        detailServiceById.setModifierName(JwtUtils.getLoginUsername());
        detailServiceById.setDealWay(simpleVo.getDealWay());
        detailServiceById.setStatus(ProductEnum.qualityStatusEmum.YJC.getCode());
        detailServiceById.setRemark(simpleVo.getRemark());
        detailServiceById.setPaperSlipPic(simpleVo.getPaperSlipPic());
        //查询任务信息
        Long qualityTestingTaskId = detailServiceById.getQualityTestingTaskId();
        WorkOrderQualityTestingTask task = this.workOrderQualityTestingTaskService.getById(qualityTestingTaskId);

        //判断是简易还是一物一检测、
        String qualityAttributes = this.productionWorkOrderService.getQualityAttributes(task.getWorkOrderId());

        ProductionWorkOrder workOrder = this.productionWorkOrderService.getById(task.getWorkOrderId());
        //一物一检测
        if ("1".equals(qualityAttributes)) {
            //合格
            if (simpleVo.getQualityTestingResult().equals(ProductEnum.qualityResultNameEmum.HG.getCode())) {
                detailServiceById.setQualityTestingResult(QualityTestingRecordDetail.QualityTestingResult.qualified);
                workOrder.setUpdateTime(LocalDateTime.now());
                workOrder.setModifier(JwtUtils.getLoginUserId());
                workOrder.setCanGetQuantity(workOrder.getCanGetQuantity() + 1);
                int okQuantity = task.getOkQuantity() == null ? 0 : task.getOkQuantity();
                task.setOkQuantity(okQuantity + 1);
                workOrder.setModifierName(JwtUtils.getLoginUsername());
            } else if (simpleVo.getQualityTestingResult().equals(ProductEnum.qualityResultNameEmum.BHG.getCode())) {
                List<QualityTestingTaskError> errorInfoVos = simpleVo.getErrorInfoVos();
                if (CollectionUtils.isNotEmpty(errorInfoVos)) {
                    //因为只有一条 所有 只做一条的处理
                    QualityTestingTaskError qualityTestingTaskError = errorInfoVos.get(0);
                    //1.判断类型有无
                    Long errorId = qualityTestingTaskError.getErrorId();
                    QueryWrapper<QualityTestingTaskError> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("error_id", errorId);
                    queryWrapper.eq("testing_task_id", task.getId());
                    QualityTestingTaskError one = qualityTestingTaskErrorService.getOne(queryWrapper);
                    if (ObjectUtil.isNotEmpty(one)) {
                        one.setUpdateTime(LocalDateTime.now());
                        one.setModifier(JwtUtils.getLoginUserId());
                        one.setModifierName(JwtUtils.getLoginUsername());
                        one.setErrorQuantity(one.getErrorQuantity() + 1);
                        //修改
                        qualityTestingTaskErrorService.updateById(one);
                    } else {
                        one = new QualityTestingTaskError();
                        one.setCreateTime(LocalDateTime.now());
                        one.setUpdateTime(LocalDateTime.now());
                        one.setErrorId(errorId);
                        one.setTestingTaskId(task.getId());
                        one.setErrorName(qualityTestingTaskError.getErrorName());
                        one.setErrorQuantity(1);
                        qualityTestingTaskErrorService.save(one);
                    }
                }
                //不合格记录不合格数 + 1
                task.setNotQuantity(task.getNotQuantity() + 1);
                task.setUpdateTime(LocalDateTime.now());
                task.setModifier(JwtUtils.getLoginUserId());
                task.setModifierName(JwtUtils.getLoginUsername());

                //报工单不合格数+1
                ProductionTheWorkOrder byId = this.productionTheWorkOrderService.getById(task.getReportOrderId());
                if (ObjectUtil.isNotEmpty(byId)) {
                    byId.setQualifiedNoQuantity(byId.getQualifiedNoQuantity() + 1);
                    byId.setUpdateTime(LocalDateTime.now());
                    byId.setModifier(JwtUtils.getLoginUserId());
                    byId.setModifierName(JwtUtils.getLoginUsername());
                    this.productionTheWorkOrderService.updateById(byId);
                }

                if (ObjectUtil.isNotEmpty(workOrder)) {
                    workOrder.setAcceptanceNoQuantity(byId.getQualifiedNoQuantity() + 1);
                    workOrder.setUpdateTime(LocalDateTime.now());
                    workOrder.setModifier(JwtUtils.getLoginUserId());
                    workOrder.setModifierName(JwtUtils.getLoginUsername());
                    //查看处置方式  0.报废 1.返修
                    if (StrUtil.isNotEmpty(simpleVo.getDealWay()) && "0".equals(simpleVo.getDealWay())) {
                        //报废 报废数 + 1
                        int ngQuantity = task.getNgQuantity()==null?0:task.getNgQuantity();
                        task.setNgQuantity(ngQuantity+1);
                        workOrder.setScrapQuantity(workOrder.getScrapQuantity() + 1);

                    } else if (StrUtil.isNotEmpty(simpleVo.getDealWay()) && "1".equals(simpleVo.getDealWay())) {
                        int returnQuantity = task.getReturnQuantity()==null?0:task.getReturnQuantity();
                        task.setReturnQuantity(returnQuantity+1);
                        workOrder.setRepairsQuantity(workOrder.getRepairsQuantity() + 1);
                    }
                }
                detailServiceById.setQualityTestingResult(QualityTestingRecordDetail.QualityTestingResult.unqualified);
            } else {
                detailServiceById.setQualityTestingResult(QualityTestingRecordDetail.QualityTestingResult.other);
            }
            //修改开工单
            productionWorkOrderService.updateById(workOrder);
            //修改质检任务
            workOrderQualityTestingTaskService.updateById(task);
            //修改质检记录
            qualityTestingRecordDetailService.updateById(detailServiceById);


            //1. 覆盖检测结果
            QueryWrapper<QualityTestingRecordValue> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("testing_record_detail_id", simpleVo.getRecordId());
            qualityTestingRecordValueService.remove(queryWrapper);
            //2. 添加新的
            List<QualityTestingRecordValue> values = new ArrayList<>();
            List<QualityDetailValueInfoVo> detailValueInfoVos = simpleVo.getDetailValueInfoVos();
            detailValueInfoVos.forEach(info -> {
                QualityTestingRecordValue value = new QualityTestingRecordValue();
                value.setCreator(JwtUtils.getLoginUserId());
                value.setCreatorName(JwtUtils.getLoginUsername());
                value.setCreateTime(LocalDateTime.now());
                value.setUpdateTime(LocalDateTime.now());
                value.setNo(value.getNo());
                String todayDt = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
                value.setDay(Integer.valueOf(todayDt));
                value.setProcessQualityId(info.getProcessQualityId());
                value.setTestingRecordDetailId(detailServiceById.getId());
                value.setProcessQualityValueName(info.getProcessQualityValueName());
                value.setProcessQualityName(info.getProcessQualityName());
                value.setRemark(info.getRemark());
                value.setFileUrl(info.getFileUrl());
                value.setFileName(info.getFileName());
                value.setItemType(info.getItemType());
                value.setImportance(info.getImportance());

                //将质检相关参数冗余 进入表中
                value.setWay(info.getWay());
                value.setStandard(info.getStandard());
                value.setUtensil(info.getUtensil());

                values.add(value);
            });

            //保存质检项信息
            qualityTestingRecordValueService.saveBatch(values);

            //查询当前任务的剩余质检个数
            Integer countNo = qualityTestingRecordValueService.getNoQualityCount(detailServiceById.getQualityTestingRecordId());
            if (countNo <= 0) {
                //修改当前任务为已完成
                WorkOrderQualityTestingTask byId = this.workOrderQualityTestingTaskService.getById(detailServiceById.getQualityTestingTaskId());
                byId.setUpdateTime(LocalDateTime.now());
                byId.setStatus(WorkOrderQualityTestingTask.Status.finish);
                boolean updated = workOrderQualityTestingTaskService.updateById(byId);
                if (updated) {
                    return 1;
                }else {
                    return 0;
                }

            } else {
                return 1;
            }
        }
        //简易检测
        else {
            detailServiceById.setQualityTestingResult(QualityTestingRecordDetail.QualityTestingResult.other);
            //任务不合格记录不合格数 + 1
            task.setNotQuantity(task.getNotQuantity() + simpleVo.getNgQuantity() + simpleVo.getReturnQuantity());
            task.setUpdateTime(LocalDateTime.now());
            task.setModifier(JwtUtils.getLoginUserId());
            task.setModifierName(JwtUtils.getLoginUsername());
            task.setNgQuantity(simpleVo.getNgQuantity());
            task.setReturnQuantity(simpleVo.getReturnQuantity());
            task.setReturnWarehouseType(simpleVo.getReturnWarehouseType());
            task.setOkWarehouseType(simpleVo.getOkWarehouseType());
            task.setNgWarehouseType(simpleVo.getNgWarehouseType());
            task.setOkQuantity(simpleVo.getOkQuantity());

            this.workOrderQualityTestingTaskService.updateById(task);

            //报工单不合格数
            ProductionTheWorkOrder byId = this.productionTheWorkOrderService.getById(task.getReportOrderId());
            if (ObjectUtil.isNotEmpty(byId)) {
                byId.setQualifiedNoQuantity(byId.getQualifiedNoQuantity() + simpleVo.getNgQuantity() + simpleVo.getReturnQuantity());
                byId.setUpdateTime(LocalDateTime.now());
                byId.setModifier(JwtUtils.getLoginUserId());
                byId.setModifierName(JwtUtils.getLoginUsername());
                this.productionTheWorkOrderService.updateById(byId);
            }

            // 添加简易质检部分
            List<QualityTestingTaskError> errorInfoVos = simpleVo.getErrorInfoVos();
            if (CollectionUtils.isNotEmpty(errorInfoVos)) {
                for (QualityTestingTaskError errorInfoVo : errorInfoVos) {
                    errorInfoVo.setTestingTaskId(task.getId());
                }
                qualityTestingTaskErrorService.saveBatch(errorInfoVos);
            }

            //开工单
            if (ObjectUtil.isNotEmpty(workOrder)) {
                //不合格数
                workOrder.setAcceptanceNoQuantity(byId.getQualifiedNoQuantity() + simpleVo.getNgQuantity() + simpleVo.getReturnQuantity());
                workOrder.setUpdateTime(LocalDateTime.now());
                workOrder.setModifier(JwtUtils.getLoginUserId());
                //合格数
                workOrder.setCanGetQuantity(workOrder.getCanGetQuantity() + simpleVo.getOkQuantity());
                workOrder.setModifierName(JwtUtils.getLoginUsername());
                //查看处置方式  0.报废 1.返修
                if (StrUtil.isNotEmpty(simpleVo.getDealWay()) && "0".equals(simpleVo.getDealWay())) {
                    workOrder.setScrapQuantity(workOrder.getScrapQuantity() + simpleVo.getNgQuantity());
                } else if (StrUtil.isNotEmpty(simpleVo.getDealWay()) && "1".equals(simpleVo.getDealWay())) {
                    workOrder.setRepairsQuantity(workOrder.getRepairsQuantity() + simpleVo.getReturnQuantity());
                }
                this.productionWorkOrderService.updateById(workOrder);
            }

            detailServiceById.setQualityTestingResult(QualityTestingRecordDetail.QualityTestingResult.other);
            detailServiceById.setRemark(simpleVo.getRemark());
            boolean b = qualityTestingRecordDetailService.updateById(detailServiceById);
            if (b) {
                WorkOrderQualityTestingTask qualityTestingTask = this.workOrderQualityTestingTaskService.getById(detailServiceById.getQualityTestingTaskId());
                qualityTestingTask.setUpdateTime(LocalDateTime.now());
                qualityTestingTask.setStatus(WorkOrderQualityTestingTask.Status.finish);
                boolean updated = workOrderQualityTestingTaskService.updateById(qualityTestingTask);
                if (updated) {
                    return 1;
                }
            }
        }
        return 0;
    }


    /**
     * 查询任务的基本信息
     *
     * @param taskId
     * @return
     */
    @Override
    public QualityTaskDetailRecordVo getTaskDetailRecord(Long taskId) {
        //1. 查询基本任务信息
        JsonResult<List<Map<String, String>>> roleAllMap = userClient.getRoleAllMap();
        List<Map<String, String>> roles = new ArrayList<>();
        if (roleAllMap.getCode() == 200) {
            roles = roleAllMap.getData();
        }
        QualityTaskDetailRecordVo taskDetailRecord = baseMapper.getTaskDetailRecord(taskId);
        //2. 补充详细信息
        List<QualityTestingRecordDetailVO> qualityTestingRecordDetails = qualityTestingRecordDetailService.getQualityTestingRecordDetail(taskDetailRecord.getRecordId());
        if (CollectionUtils.isNotEmpty(qualityTestingRecordDetails)) {
            List<QualityTaskDetailInfoVo> list = new ArrayList<>();
            qualityTestingRecordDetails.forEach(info -> {
                QualityTaskDetailInfoVo vo = new QualityTaskDetailInfoVo();
                BeanUtil.copyProperties(info, vo);
                vo.setStatusDesc(ProductEnum.qualityStatusEmum.getNameByCode(vo.getStatus()));
                if (info.getQualityTestingResult() != null) {
                    if ("qualified".equals(info.getQualityTestingResult().name())) {
                        vo.setQualityTestingResultName("合格");
                    } else if ("unqualified".equals(info.getQualityTestingResult().name())) {
                        vo.setQualityTestingResultName("不合格");
                    } else {
                        vo.setQualityTestingResultName("其他");
                    }
                }
                list.add(vo);
            });
            taskDetailRecord.setTaskDetailInfoVos(list);
        }
        //3.补充时间线
        QualityTimeDetailInfoVo infoVo = baseMapper.getTimeInfo(taskId);


        //4. 判断状态
        if (taskDetailRecord.getStatus().equals(String.valueOf(MaintenanceEnum.QualityStatus.WC.getCode()))) {
            QualityTimeDetailInfoVo finshInfo = baseMapper.selectLastDetailFinshInfo(taskDetailRecord.getRecordId());
            infoVo.setCheckDepName(finshInfo.getCheckDepName());
            infoVo.setCheckTime(finshInfo.getCheckTime());
            infoVo.setCheckName(finshInfo.getCheckName());
            infoVo.setCheckPostName(finshInfo.getCheckPostName());
        }
        if (StrUtil.isNotEmpty(infoVo.getCreateTime())) {
            infoVo.setCreateTime("(" + infoVo.getCreateTime() + ")");
        }
        if (StrUtil.isNotEmpty(infoVo.getGetTime())) {
            infoVo.setGetTime("(" + infoVo.getGetTime() + ")");
        }
        if (StrUtil.isNotEmpty(infoVo.getCheckTime())) {
            infoVo.setCheckTime("(" + infoVo.getCheckTime() + ")");
        }

        //查询异常信息
        QueryWrapper<QualityTestingTaskError> taskErrorQueryWrapper = new QueryWrapper<>();
        taskErrorQueryWrapper.eq("testing_task_id", taskId);
        taskErrorQueryWrapper.eq("is_deleted",false);
        List<QualityTestingTaskError> list = qualityTestingTaskErrorService.list(taskErrorQueryWrapper);
        taskDetailRecord.setQualityTestingTaskErrors(list);

        for (Map<String, String> role : roles) {
            if (StringUtils.isNotBlank(infoVo.getCreatePostName())) {
                if (role.get("id").equals(infoVo.getCreatePostName())) {
                    infoVo.setCreatePostName(role.get("name"));
                }
            }
            if (StringUtils.isNotBlank(infoVo.getGetPostName())) {
                if (role.get("id").equals(infoVo.getGetPostName())) {
                    infoVo.setGetPostName(role.get("name"));
                }
            }
            if (StringUtils.isNotBlank(infoVo.getCheckPostName())) {
                if (role.get("id").equals(infoVo.getCheckPostName())) {
                    infoVo.setCheckPostName(role.get("name"));
                }
            }
            if (StringUtils.isNotBlank(infoVo.getCreateDepName())) {
                if (role.get("id").equals(infoVo.getCreateDepName())) {
                    infoVo.setCreateDepName(role.get("name"));
                }
            }
            if (StringUtils.isNotBlank(infoVo.getGetDepName())) {
                if (role.get("id").equals(infoVo.getGetDepName())) {
                    infoVo.setGetDepName(role.get("name"));
                }
            }
            if (StringUtils.isNotBlank(infoVo.getCheckDepName())) {
                if (role.get("id").equals(infoVo.getCheckDepName())) {
                    infoVo.setCheckDepName(role.get("name"));
                }
            }
        }
        taskDetailRecord.setQualityTimeDetailInfoVo(infoVo);
        return taskDetailRecord;
    }

    /**
     * 查询新的质检任务明细列表
     *
     * @param pg
     * @param paramMap
     * @return
     */
    @Override
    public IPage<QualityTestingRecordDetailSearchVO> pageList4appNew(Page<QualityTestingRecordDetailSearchVO> pg, Map paramMap) {
        List<QualityTestingRecordDetailSearchVO> list = baseMapper.pageList4appNew(pg, paramMap);
        pg.setRecords(list);
        return pg;
    }

    /**
     * 关闭质检任务
     *
     * @param id 质检任务id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int close(Long id) {
        //只有认领了的 才能被关闭
        WorkOrderQualityTestingTask testingTask = this.workOrderQualityTestingTaskService.getById(id);
        //不为送检中
        if (testingTask.getStatus().getValue().equals(WorkOrderQualityTestingTask.Status.confirm.getValue())) {
            return 2;
        }
        //1. 设置为关闭
        testingTask.setModifier(JwtUtils.getLoginUserId());
        testingTask.setModifierName(JwtUtils.getLoginUsername());
        testingTask.setUpdateTime(LocalDateTime.now());
        testingTask.setStatus(WorkOrderQualityTestingTask.Status.close);
        boolean updated = this.workOrderQualityTestingTaskService.updateById(testingTask);
        if (updated) {
            //2. 关闭任务后 (一物一检的情况)返还未质检的数据给开工单
            String qualityAttributes = this.productionWorkOrderService.getQualityAttributes(testingTask.getWorkOrderId());
            if (StrUtil.isNotBlank(qualityAttributes) && MaintenanceEnum.qualityNatureEmum.YWYJ.getCode().equals(qualityAttributes)) {
                //查询未质检的数量
                int count = this.baseMapper.getNotCheckQuatityBy(testingTask.getId());
                //返还数据给开工单
                if (count > 0) {
                    ProductionWorkOrder byId = this.productionWorkOrderService.getById(testingTask.getWorkOrderId());
                    byId.setCanGetQuantity(byId.getCanGetQuantity() + count);
                    boolean isOk = this.productionWorkOrderService.updateById(byId);
                    if (isOk) {
                        return 1;
                    }
                }
            }
            //如果是简易质检的话
            else {
                ProductionWorkOrder byId = this.productionWorkOrderService.getById(testingTask.getWorkOrderId());
                byId.setCanGetQuantity(byId.getCanGetQuantity() + testingTask.getSubmissionQuantity());
                boolean isOk = this.productionWorkOrderService.updateById(byId);
                if (isOk) {
                    return 1;
                }
            }
        }
        return 0;
    }

    /**
     * 获取开工单质检错误信息
     *
     * @param processId 开工单信息
     * @return
     */
    @Override
    public List<ProAbnormalCause> getAbnormalCauseBy(Long processId) {
        return this.baseMapper.getAbnormalCauseBy(processId);
    }
}
